/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.cadastro.DAO;

import br.com.cadastro.entity.Usuario;
import br.com.cadastro.util.HibernateUtil;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;

/**
 *
 * @author Dinarth
 */
public class UsuarioDAO {

    private Session sessao;
    private Transaction trans;
    private List<Usuario> lista;

    public void addUsuario(Usuario u) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            trans = sessao.beginTransaction();

            Usuario usuario = new Usuario();
            usuario.setUsuario(u.getUsuario());
            usuario.setSenha(u.getSenha());
            usuario.setPermissao(u.getPermissao());

            sessao.save(usuario);
            trans.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();
        }
    }

    public List<Usuario> getList() {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();

            Criteria cri = sessao.createCriteria(Usuario.class);
            cri.addOrder(Order.asc("usuario"));

            this.lista = cri.list();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();
        }
        return lista;
    }

    public void removeUsuario(Usuario u) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            trans = sessao.beginTransaction();

            sessao.delete(u);
            trans.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();

        }
    }

    public void changeSenha(Usuario u) {
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            trans = sessao.beginTransaction();

            sessao.update(u);
            trans.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sessao.close();
        }
        
    }
}


